﻿var teamUsers;
var inUploading = false;
$(function () {
    $("#tabs").tabs();

    $('#divDetail').dialog({
        width: 950,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    });

    $('#divNextStep').dialog({
        width: 450,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    });

    $('#divAttachment').dialog({
        width: 500,
        autoOpen: false,
        modal: true,
        buttons: {
        }
    });

    $("input[name=NextType]").click(function () {
        $("select").removeClass("redBorder");
        switch ($("input[name=NextType]:checked").attr("id")) {
            case "NextType1":
                $("#NextStep").show();
                $("#NextStep").change();
                break;
            case "NextType2":
                $("#NextStep").hide();
                if (teamUsers != null) {
                    $("#UserId").empty();
                    $("#UserId").append("<option></option>");

                    for (var r in teamUsers) {
                        $("#UserId").append("<option value='" + teamUsers[r].ItemValue + "'>" + teamUsers[r].ItemText + "</option>");
                    }
                }
                break;
            default:
                break;
        }
    });

    $("#btnUpload").click(function () {
        ajaxFileUpload();
    });

    $("#btnOrderMemo").click(function () {
        $('#errorMessageMemo').html('');
        $('#OrderMemo').removeClass('redBorder');
        if (checkRequired('MemoPanel', 'errorMessageMemo') == false) {
            return;
        }
        if (!confirm("提示:\n备忘信息所有人可见。确认添加吗？")) {
            return;
        }
        $.ajax({
            url: "/Order/AddOrderMemo",
            type: 'POST',
            cache: false,
            dataType: 'json',
            async: false,
            data: { OrderNo: $("#OrderNo").val(), Memo: $("#OrderMemo").val() },
            success: function (result) {
                if (result.code == 0) {
                    $("#OrderMemo").val("");
                    $("<tr><td>" + result.data.Addition1 + "</td><td>" + result.data.Addition2 + "</td><td>" + result.data.Addition3 + "</td></tr>").appendTo($("#dOrderMemo"));
                }
                else {                    
                    $('#errorMessageMemo').html('保存失败');
                }
            },
            error: function (e) {               
                $('#errorMessageMemo').html('保存失败');
            }
        });


    });

    $("#btnSave").click(function () {
        $("select").removeClass("redBorder");
        var nextType = $("input[name=NextType]:checked").val();
        var isEndPoint = $("#isEndPoint").val();

        if (nextType == "1") {
            if ($("#NextStep").val() == "") {
                $("#NextStep").addClass("redBorder");
                return;
            }
            //console.log(isEndPoint);
            if (isEndPoint == "0" && $("#UserId").val() == "") {
                $("#UserId").addClass("redBorder");
                return;
            }
        }
        else {
            if ($("#UserId").val() == "") {
                $("#UserId").addClass("redBorder");
                return;
            }
        }

        $.ajax({
            url: "/Order/OrderFlowToNext",
            type: 'POST',
            cache: false,
            dataType: 'json',
            async: false,
            data: { OrderNo: $("#OrderNo").val(), NextType: nextType, WorkFlowStepNo: $("#NextStep").val(), UserId: $("#UserId").val() },
            success: function (result) {
                if (result.code == 0) {
                    window.location.reload();
                }
                else {
                    alert("保存失败,请稍后重试");
                    $('#divWorkFlow').dialog('close');
                }
            },
            error: function (e) {
                alert("保存失败,请稍后重试");
                $('#divWorkFlow').dialog('close');
            }
        });
    });


    $("#NextStep").change(function () {
        $("select").removeClass("redBorder");
        $("#UserId").empty();
        $("#UserId").append("<option></option>");
        $("#isEndPoint").val("0");
        if ($("#NextStep").val() == "") {
            return;
        }

        $.ajax({
            url: "/Order/GetWorkFlowStepUsers",
            type: 'GET',
            cache: false,
            dataType: 'json',
            async: false,
            data: { WorkFlowStepNo: $("#NextStep").val() },
            success: function (result) {
                if (result.code == 0) {

                    $("#isEndPoint").val(result.isEndPoint);
                    if (result.isEndPoint == "1") {
                        $("#UserId").hide();
                    }
                    else {
                        $("#UserId").show();
                        for (var r in result.data) {
                            $("#UserId").append("<option value='" + result.data[r].ItemValue + "'>" + result.data[r].ItemText + "</option>");
                        }
                    }
                }
                else {

                }
            },
            error: function (e) {

            }
        });
    });
});

function ShowDetail(id) {
    $("#OrderNo").val(id);
    $.ajax({
        url: "/MySpace/GetDetail",
        type: 'POST',
        cache: false,
        data: { OrderNo: id },
        success: function (result) {
            if (result.code == 0) {
                $("#dStatus").html(result.data.StatusDescription);
                $("#dOrderNo").html(result.data.OrderNo);
                $("#dOrderName").html(result.data.OrderName);
                $("#dCustomer").html(result.data.CustomerShortName);
                $("#dContact").html(result.data.Contact);
                $("#dCreatedTime").html(result.data.CreatedTimeString);
                $("#dTransactionDate").html(result.data.TransactionDateString);
                $("#dCreator").html(result.data.Creator);
                $("#dDetail").html(result.data.Detail);
                $("#dNumber").html(result.data.Number);
                $("#dExpectDeliveryDate").html(result.data.ExpectDeliveryDateString);
                $("#dHistory").html(result.data.History);
                $("#dMemo").html(result.data.Memo);
                GenerateWorkFlowSteps(result.data.steps);
                $("#dQueryURL").html("");
                var a = $("<a target='_blank' href='" + result.data.QueryURL + "'>" + result.data.QueryURL + "</a>").appendTo($("#dQueryURL"));
                $("#dOrderMemo").html("");
                for (var r in result.data.OrderMemos) {
                    $("<tr><td>" + result.data.OrderMemos[r].Addition1 + "</td><td>" + result.data.OrderMemos[r].Addition2 + "</td><td>" + result.data.OrderMemos[r].Addition3 + "</td></tr>").appendTo($("#dOrderMemo"));
                }
                var t = $("#tdAttachment");
                t.html("");
                for (var r in result.data.Attachments) {
                    var a = $("<div title='点击下载'><img src='" + result.data.Attachments[r].Addition1 + "' alt=''/><a href='#' style='text-decoration:underline;' onclick=\"javascript:return DownLoadFile('" + result.data.Attachments[r].ItemValue + "');\">" + result.data.Attachments[r].ItemText + "</a> (" + result.data.Attachments[r].Addition2 + ")</div>");
                    a.appendTo(t);
                }

                $('#divDetail').dialog('open');
            }
            else {
                alert("获取信息失败.");
            }

        },
        error: function (e) {
            alert("获取信息失败.");
        }
    });
}

function NextStep(id) {
    $("select").removeClass("redBorder");
    $("#OrderNo").val(id);
    $.ajax({
        url: "/Order/GetOrderNextStep",
        type: 'GET',
        cache: false,
        data: { OrderNo: id },
        success: function (result) {
            if (result.code == 0) {
                $("#NextType").val("1");
                $("#NextStep").empty();
                $("#NextStep").append("<option></option>");
                $("#UserId").empty();
                teamUsers = result.data.TeamUserIds;
                for (var r in result.data.FollowUps) {
                    $("#NextStep").append("<option value='" + result.data.FollowUps[r].ItemValue + "'>" + result.data.FollowUps[r].ItemText + "</option>");
                }

                $('#divNextStep').dialog('open');
            }
            else {
                alert("获取信息失败.");
            }

        },
        error: function (e) {
            alert("获取信息失败.");
        }
    });
}

function ajaxFileUpload() {
    $("#errorMessageAttachment").html("");

    if ($("#fileToUpload").val() == "") {
        $("#errorMessageAttachment").html("请选择上传文件");
        return;
    }

    var point = $("#fileToUpload").val().lastIndexOf(".");
    var type = $("#fileToUpload").val().substr(point).toLowerCase();

    if (type == ".exe" || type == ".bat" || type == ".msi") {
        $("#errorMessageAttachment").html("文件类型不允许");
        return;
    }
    $("#loading").show();

    $('#loading').dialog('open');
    $.ajaxFileUpload({
        url: '/Order/FileUpload',
        secureuri: false,
        fileElementId: 'fileToUpload',
        data: { OrderNo: $("#OrderNo").val() },
        dataType: 'json',
        success: function (d, status) {
            var data = JSON.parse(d);
            data = data.Data;
            if (data.code == "1") {
                $("#divAttachment input").removeAttr("disabled");
                inUploading = false;
                $("#errorMessageAttachment").html(data.message);
                $("#loading").hide();
            }
            else if (data.code == "0") {
                $("#divAttachment input").removeAttr("disabled");
                inUploading = false;
                $("#loading").hide();
                alert("上传成功！");
                $('#divAttachment').dialog('close');
            }
        },
        error: function (data, status, e) {
            console.log(data);
            console.log(status);
            console.log(e);
            $("#divAttachment input").removeAttr("disabled");
            inUploading = false;
            $("#errorMessageAttachment").html("上传时发生错误");
            $("#loading").hide();
        }
    });

    $("#divAttachment input").attr("disabled", "disabled");
    inUploading = true;
    return false;
}

function ShowAttachment(OrderNo) {
    $("#OrderNo").val(OrderNo);

    $.ajax({
        url: "/Order/GetOrderAttachments",
        type: 'GET',
        cache: false,
        data: { OrderNo: $("#OrderNo").val() },
        success: function (result) {
            if (result.code == 0) {
                $("#dAttachment").html("");

                if (result.data.length > 0) {
                    for (var r in result.data) {
                        var tr = $("<tr id='" + result.data[r].ItemValue + "'></tr>");
                        var td = $("<td style='text-align: center;'></td>");
                        var image = $("<img src='" + result.data[r].Addition1 + "' alt=''>");
                        image.appendTo(td);
                        td.appendTo(tr);
                        td = $("<td></td>");
                        td.html(result.data[r].ItemText);
                        td.appendTo(tr);
                        td = $("<td></td>");
                        td.html(result.data[r].Addition2);
                        td.appendTo(tr);
                        td = $("<td></td>");
                        var tno = result.data[r].ItemValue;
                        var t = $("<a href='#' onclick=\"javascript:return DownLoadFile('" + tno + "');\">下载</a>");
                        t.appendTo(td);

                        t = $("<a href='#' style='margin-left:5px;' onclick=\"javascript:return DeleteFile('" + tno + "','" + result.data[r].ItemText + "');\">删除</a>");

                        t.appendTo(td);
                        td.appendTo(tr);

                        tr.appendTo($("#dAttachment"));
                    }
                }
                $('#divAttachment').dialog('open');
            }
            else {
                alert("获取信息失败.");
            }

        },
        error: function (e) {
            alert("获取信息失败.");
        }
    });
}

function DeleteFile(no, name) {

    if (inUploading) {
        return false;
    }

    if (confirm('确定删除附件 '+ name +' 吗？')) {
        $.ajax({
            url: "/Order/DeleteAttachment",
            type: 'GET',
            cache: false,
            data: { FileNo: no, OrderNo: $("#OrderNo").val() },
            success: function (result) {
                if (result.code == 0) {
                    $("#tAttachment").find("tr[id=" + result.FileNo + "]").remove();
                }
                else {
                    alert("删除失败.");
                }

            },
            error: function (e) {
                alert("删除失败.");
            }
        });
    }
}

function DownLoadFile(no) {

    if (inUploading) {
        return false;
    }

    location.href = "/Order/DownLoadAttachment?FileNo=" + no;
}